package com.cuitrip.business.home.my.card;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.app.base.UnitUtils;
import com.cuitrip.business.home.recommend.model.ListResponse;
import com.cuitrip.business.pay.model.DiscountItem;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.time.InputTime;
import com.cuitrip.util.time.OutputTime;
import com.cuitrip.util.time.TimeUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by MiJack on 2015/10/19.
 */
public class CardActivity extends CustomUiFragmentActivity implements IProxyCallback {

    private static final String TAG = "CardActivity";
    private static final String SELECT_MODE = "SELECT_MODE";
    private List<DiscountItem> discountItems;
    private boolean selectMode;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, CardActivity.class);
        context.startActivity(intent);
    }
    @Bind(R.id.listView)
    ListView listView;

    @Bind(R.id.state_layout)
    StateLayout mStateLayout;

    CardAdapter cardAdapter;

    private ApiProxy mApiProxy=new ApiProxy(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        selectMode = getIntent().getBooleanExtra(SELECT_MODE, false);
        super.onCreate(savedInstanceState,R.layout.ct_activity_card);
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        cardAdapter = new CardAdapter();
        listView.setAdapter(cardAdapter);
        //mClient = new AsyncHttpClient();
        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                requestValidCoupon();
            }
        });
        requestValidCoupon();
    }

    @Override
    public void initListener() {
        if (selectMode){
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                DiscountItem discountItem=discountItems.get(position);
                String discountId = discountItem.getCode();
                Intent intent=new Intent();
                intent.putExtra("discountItem",discountItem);
                intent.putExtra("discountMoney",discountItem.getMoney());
                intent.putExtra("discountId", discountId);
                intent.putExtra("discountMoneyType",discountItem.getMoneyType());
                setResult(RESULT_OK,intent);
                finish();
            }
        });
    }
    }

    public void requestValidCoupon(){
        mStateLayout.changeState(StateLayout.State.Loading);
        OrderBusiness.getValidCoupon(mApiProxy, UnitUtils.getSettingMoneyType());
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config=new CustomUiConfig();
        config.mTopbarLeftAreaName=getString(R.string.back_icon);
        config.mTopbarMiddleAreaName=getString(R.string.coupon);
        if (selectMode) {
            config.mRightStyle= CustomUiConfig.AreaStyle.TEXT_STYLE;
            config.mTopbarRightAreaName = getString(R.string.coupon_not_use);
        }
        return config;
    }

    @Override
    public void onTopbarRightPress() {
        if (selectMode){
            Intent intent=new Intent();
            intent.putExtra("discountMoney","0.00");
            intent.putExtra("discountId", "");
            intent.putExtra("discountMoneyType","");
            setResult(RESULT_OK,intent);
            finish();            finish();
        }
    }

    @Override
    public void onTopbarLeftPress() {
        finish();
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (response != null && response.code == CtResponseCode.RESULT_OK) {
            mStateLayout.changeState(StateLayout.State.INIT);
            if(response.result instanceof ListResponse){
                discountItems=((ListResponse<DiscountItem>)response.result).getList();
                if (discountItems.size() == 0) {
                    listView.setVisibility(View.GONE);
                    findViewById(R.id.couponBlack).setVisibility(View.VISIBLE);
                }
                cardAdapter.setDiscountItems(discountItems);
            }

        }else{
            mStateLayout.changeState(StateLayout.State.NoNetwork);
            String reason;
            if (response != null && !TextUtils.isEmpty(response.msg)) {
                reason = response.msg;
                Toast.makeText(CardActivity.this, reason, Toast.LENGTH_SHORT).show();
            }
        }
        return false;
    }

    public static void startForCard(Activity activity, int request) {
        Intent intent =new Intent(activity,CardActivity.class);
        intent.putExtra(SELECT_MODE,true);
        activity.startActivityForResult(intent,request);
    }



    private static class CardAdapter extends BaseAdapter {
        List<DiscountItem> discountItems;

        public CardAdapter() {
            discountItems = new ArrayList<>();
        }

        @Override
        public int getCount() {
            return discountItems == null ? 0 : discountItems.size();
        }

        @Override
        public DiscountItem getItem(int position) {
            return discountItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(parent.getContext());
                convertView = inflater.inflate(R.layout.ct_item_card, parent, false);
                holder = new ViewHolder();
                holder.tvMoney = (TextView) convertView.findViewById(R.id.tvMoney);
                holder.tvMoneyType = (TextView) convertView.findViewById(R.id.tvMoneyType);
                holder.tvInvalidDate = (TextView) convertView.findViewById(R.id.tvInvalidDate);
                holder.tvInvalid = (TextView) convertView.findViewById(R.id.tvInvalid);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            DiscountItem discountItem = getItem(position);
            try {
                holder.tvMoney.setText(Utils.getMoneyFormat(discountItem.getMoney()));
            }catch (Exception e){

            }
            holder.tvMoneyType.setText(discountItem.getMoneyType());
            String date = discountItem.getInvalidDate();
            holder.tvInvalidDate.setText(date);
            Resources resources = parent.getResources();
            boolean enable = true;
            try {
                long invalidDate = Long.valueOf(date);
                 enable = System.currentTimeMillis() <= invalidDate;
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
                holder.tvInvalidDate.setText(resources.getString(R.string.user_attribute_id_document_expiry)+" "+
                TimeUtil.formatTime(
                        InputTime.build(discountItem.getInvalidDate()),
                        OutputTime.getLocalInstance(OutputTime.OutputType.Type_Minute)
                ));
                holder.tvInvalid.setVisibility(enable ? View.INVISIBLE : View.VISIBLE);
                holder.tvMoney.setTextColor(enable ? ResourceUtil.getThemeColor() : resources.getColor(R.color.ganshi_ded8d7));
                holder.tvMoneyType.setTextColor(enable ? ResourceUtil.getThemeColor() : resources.getColor(R.color.ganshi_ded8d7));
                holder.tvInvalidDate.setTextColor(enable ? ResourceUtil.getColor(R.color.qiaomai_7c706e) : resources.getColor(R.color.ganshi_ded8d7));

            return convertView;
        }

        public void setDiscountItems(List<DiscountItem> discountItems) {
            this.discountItems = discountItems;
            notifyDataSetInvalidated();
        }


        private static class ViewHolder {
            public TextView tvMoney;
            public TextView tvMoneyType;
            public TextView tvInvalidDate;
            public TextView tvInvalid;
        }
    }

}
